package io.renren.modules.sys.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sun.org.apache.xpath.internal.operations.Bool;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.excel.DefaultExcelExportUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.searcher.OrderSearcher;
import io.renren.modules.sys.service.*;
import io.renren.modules.sys.vo.OrderItemDetailVO;
import io.renren.modules.sys.vo.OrderVO;
import io.renren.modules.sys.vo.OrdersDownVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.entity.OrdersEntity;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;


/**
 * 订单
 *
 * @author generator
 * @email 707069921@qq.com
 * @date 2018-10-28 12:52:38
 */
@RestController
@RequestMapping("sys/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private InvoiceInfoService invoiceInfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:orders:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = ordersService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:orders:info")
    public ModelAndView info(@PathVariable("id") Long id , ModelMap modelMap){
        /**获取订单信息*/
        OrdersEntity order = ordersService.findOrderById(id);
        modelMap.addAttribute("order" , order);
        modelMap.addAttribute("user" , sysUserService.selectById(order.getUserId()));
        modelMap.addAttribute("shop" , supplierService.selectById(order.getShopId()));
        return new ModelAndView("/modules/sys/orderitem");
    }

    /**
     * 信息
     */
    @RequestMapping("/back")
    public ModelAndView back(){
        return new ModelAndView("/modules/sys/orders");
    }


    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:orders:save")
    public R save(@RequestBody OrderVO orders){
        ValidatorUtils.validateEntity(orders, AddGroup.class);
        OrdersEntity ordersEntity = ordersService.inserOrders(orders);
        if(ordersEntity != null){
            return R.ok().put("order" , ordersEntity);
        }
        return R.error();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:orders:update")
    public R update(@RequestBody OrdersEntity orders){
        OrdersEntity order = ordersService.findOrderById(orders.getId());
        if(order == null){
            throw  new RRException("未查询到这笔订单！！！！");
        }
        order.setLogisticsFee(orders.getLogisticsFee());
        Boolean isSuccess = ordersService.updateOrder(order);
        if(isSuccess){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:orders:delete")
    public R delete(@RequestBody Long[] ids){
//        ordersService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 打印预览
     */
    @RequestMapping("/preview")
    public ModelAndView preview( Long orderId ,ModelMap modelMap ,String page){
        modelMap.addAttribute("order" , ordersService.selectOrderInfoList(orderId));
        Map<String, Object> params = new HashMap<>();
        params.put("orderId" , orderId);
        params.put("limit" , "11");
        params.put("page" , page == null ? "1" : page);


        modelMap.addAttribute("orderId" , orderId);
        PageUtils pageUtils  = orderItemService.queryOrderItemPage(params);
        modelMap.addAttribute("orderItems" , pageUtils);
        Integer countNum = 0;
        BigDecimal price = new BigDecimal("0.00");
        BigDecimal totalPrice = new BigDecimal("0.00");
        for (Object  o: pageUtils.getList()){
            OrderItemDetailVO orderItemDetailVO = (OrderItemDetailVO) o;
            countNum = countNum + orderItemDetailVO.getNumber();
            totalPrice = totalPrice.add(orderItemDetailVO.getTotalPrice());
            price = price.add(orderItemDetailVO.getPrice());

        }
        modelMap.put("countNum" , countNum);
        modelMap.put("price" , price);
        modelMap.put("totalPrice" , totalPrice);
        modelMap.addAttribute("invoice" , invoiceInfoService.findInvoiceInfoByEnable());
        return new ModelAndView("modules/sys/preview");
    }
    /**
     * 下载对账单
     */
    @RequestMapping("/download")
    public void download(OrderSearcher searcher, HttpServletResponse response) throws Exception {
        String excelName = "对账单" +  DateUtils.getDateTimeStr(new Date());
        List<OrdersDownVO> list = ordersService.selectOrderListDown(searcher);
        DefaultExcelExportUtils.exportExcel(OrdersDownVO.class,list,excelName, response);
    }



}
